package com.yangrong.thread.chapter7;

public class ImmutablePerformance {

	public static void main(String[] args) throws InterruptedException {
		long startTimestamp = System.currentTimeMillis();

		// Immutable设计模式和使用synchronized
		// 15064 synchronized
		// 16024 Immutable
		// double thread
		// 40620 synchronized
		// 43678 Immutable
		SyncObj syncObj = new SyncObj();
		syncObj.setName("Alex");
//		ImmutableObj immutableObj = new ImmutableObj("Alex");
//		for (long l = 0L; l < 1000000; l++) {
//			System.out.println(syncObj.toString());
//		}

		Thread t1 = new Thread() {
			public void run() {
				for (long l = 0L; l < 1000000; l++) {
					System.out.println(Thread.currentThread().getName() + "=" + syncObj.toString());
				}
			};
		};

		Thread t2 = new Thread() {
			public void run() {
				for (long l = 0L; l < 1000000; l++) {
					System.out.println(Thread.currentThread().getName() + "=" + syncObj.toString());
				}
			};
		};

		t1.start();
		t2.start();
		t1.join();
		t2.join();

		long endTimestamp = System.currentTimeMillis();
		System.out.println("Elapsed time " + (endTimestamp - startTimestamp));
	}
}

final class ImmutableObj {
	private final String name;

	ImmutableObj(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "ImmutableObj [name=" + name + "]";
	}

}

class SyncObj {
	private String name;

	public synchronized void setName(String name) {
		this.name = name;
	}

	@Override
	public synchronized String toString() {
		return "SyncObj [name=" + name + "]";
	}

}
